package com.ideal.manage.esms.service.project;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ideal.manage.esms.bean.DTO.DeployTree;
import com.ideal.manage.esms.bean.DTO.PageDto;
import com.ideal.manage.esms.bean.project.EquipmentManage;
import com.ideal.manage.esms.bean.project.EquipmentMessageConf;
import com.ideal.manage.esms.bean.project.EquipmentTemperatureConf;
import com.ideal.manage.esms.bean.project.ProjectManage;
import com.ideal.manage.esms.bean.sys.User;
import com.ideal.manage.esms.config.shiro.MyShiroRealm;
import com.ideal.manage.esms.repository.framework.MySpecification;
import com.ideal.manage.esms.repository.framework.SpecificationOperator;
import com.ideal.manage.esms.repository.project.EquipmentManageRepository;
import com.ideal.manage.esms.repository.project.EquipmentMessageConfRepository;
import com.ideal.manage.esms.repository.project.EquipmentTemperatureConfRepository;
import com.ideal.manage.esms.repository.project.ProjectManageRepository;
import com.ideal.manage.esms.repository.system.UserRepository;
import com.ideal.manage.esms.util.ExportTextUtil;
import com.ideal.manage.esms.util.HttpRequests;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created By Dai On 2018/4/25
 * Remark: 工程配置 - 对象管理 - 设备管理 Service
 */
@Service
public class EquipmentManageService {
    private Logger logger = LoggerFactory.getLogger(EquipmentManageService.class);
    @Autowired
    private EquipmentManageRepository equipmentManageRepository;
    @Autowired
    private ProjectManageRepository projectManageRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private EquipmentTemperatureConfRepository equipmentTemperatureConfRepository;
    @Autowired
    private EquipmentMessageConfRepository equipmentMessageConfRepository;

    @Value("${equipmentManage.file.path}")
    private String filePath;

    /**
     * 工程配置 -> 对象管理 -> 设备管理 -> 数据表
     *
     * @param pageNum
     * @param request
     * @return
     */
    public PageDto findAll(int pageNum, HttpServletRequest request) {
        Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
        List<SpecificationOperator> operators = HttpRequests.getParametersStartingWith(request, "Q_");
        //增加删除标识的过滤
        SpecificationOperator isValid = new SpecificationOperator("isValid", "1", "EQ");
        operators.add(isValid);
        MySpecification<EquipmentManage> mySpecifications = new MySpecification<>(operators);
        Pageable pageable = new PageRequest(pageNum, 10, sort);
        Page<EquipmentManage> page = equipmentManageRepository.findAll(mySpecifications, pageable);
        //设置PageDto
        List<EquipmentManage> parameters = page.getContent();
        long total = page.getTotalElements();
        PageDto pageDto = new PageDto();
        pageDto.setRows(parameters);
        pageDto.setTotal(total);
        return pageDto;
    }

    /**
     * 将项目的子节点加入这个这个树里面
     *
     * @param id
     * @param ztreeDtos
     * @return
     */
    public List findAllByProjectId(String id, List ztreeDtos) {
        List<SpecificationOperator> operators = new ArrayList<SpecificationOperator>() {{
            add(new SpecificationOperator("isValid", "1", "EQ"));
            add(new SpecificationOperator("project.id", id, "EQ"));
        }};
        MySpecification<EquipmentManage> mySpecifications = new MySpecification<>(operators);
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        List<EquipmentManage> list = equipmentManageRepository.findAll(mySpecifications, sort);
        list.forEach(equipmentManage -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", equipmentManage.getId());
            if (equipmentManage.getParent() == null) {
                jsonObject.put("pId", id);
            } else {
                jsonObject.put("pId", equipmentManage.getParent().getId());
            }
            jsonObject.put("name", equipmentManage.getName());
            jsonObject.put("type", equipmentManage.getEquipmentType());
            jsonObject.put("equipmentType", equipmentManage.getEquipmentType());
            jsonObject.put("communication", equipmentManage.getCommunication() == null ? "" : equipmentManage.getCommunication());
            jsonObject.put("messageName", equipmentManage.getMessageName() == null ? "" : equipmentManage.getMessageName());
            ztreeDtos.add(jsonObject);
        });
        return ztreeDtos;
    }

    /**
     * 工程配置 -> 对象管理 -> 项目管理 -> 编辑设备树 -> 导出树结构
     *
     * @param response
     * @param id
     */
    public void exportTree(HttpServletResponse response, String id) {
        String str = "";
        ProjectManage projectManage = projectManageRepository.findOne(id);
        str += "项目\t" + projectManage.getName() + "\n";
        List<EquipmentManage> equipmentManages = equipmentManageRepository.findByProjectId(id);
        for (EquipmentManage equipmentManage : equipmentManages) {
            switch (equipmentManage.getEquipmentType()) {
                case "1":
                    str += "变流器\t" + equipmentManage.getName() + "\n";
                    break;
                case "2":
                    str += "电池包\t" + equipmentManage.getName() + "\n";
                    break;
                case "3":
                    str += "电池组\t" + equipmentManage.getName() + "\t" + equipmentManage.getParent().getName() + "\n";
                    break;
                case "4":
                    str += "电池单体\t" + equipmentManage.getName() + "\t" + equipmentManage.getParent().getName() + "\n";
                    break;
            }
        }
        ExportTextUtil.writeToTxt(response, str, "导出树_" + projectManage.getName());
//        logger.info("导出树_" + projectManage.getName() + "文件内容\n" + str);
    }

    /**
     * 工程配置 -> 对象管理 -> 项目管理 -> 编辑设备树 -> 导入树结构
     *
     * @param file
     * @param id
     */
    public String importTree(MultipartFile file, String id) {
        if (file == null) {
            return "文件读取失败，请稍后再试";
        }
        //获取当前项目
        ProjectManage projectManage = projectManageRepository.findOne(id);
        String projectManageName = projectManage.getName();
        //获取当前子元素
        List<EquipmentManage> equipmentManages = equipmentManageRepository.findByProjectId(id);
        //获取当前登录用户
        MyShiroRealm.ShiroUser shiroUser = (MyShiroRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        User user = userRepository.findOne(shiroUser.getId());
        //创建时间
        Date date = new Date();
        //准备工作
        EquipmentManage equipmentManage = null;
        List<EquipmentManage> newList = new ArrayList<>();
        //把所有的子元素放到newList里面
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(file.getInputStream()));
            String readLine = "";
            //获取文件的内容
            String fileContext = "";
            // 所有的集合
            while (StringUtils.isNotBlank(readLine = bufferedReader.readLine())) {
                String[] strings = readLine.split("\t");
                fileContext += readLine + "\n";
                switch (strings[0]) {
                    case "项目":
                        if (!projectManageName.equals(strings[1])) return "项目名错误";
                        break;
                    case "变流器":
                        equipmentManage = new EquipmentManage();
                        equipmentManage.setEquipmentType("1");
                        equipmentManage.setName(strings[1]);
                        equipmentManage.setProject(projectManage);
                        equipmentManage.setCreateUser(user);
                        equipmentManage.setCreateTime(date);
                        equipmentManage.setUpdateTime(date);
                        newList.add(equipmentManage);
                        break;
                    case "电池包":
                        equipmentManage = new EquipmentManage();
                        equipmentManage.setEquipmentType("2");
                        equipmentManage.setName(strings[1]);
                        equipmentManage.setProject(projectManage);
                        equipmentManage.setCreateUser(user);
                        equipmentManage.setCreateTime(date);
                        equipmentManage.setUpdateTime(date);
                        newList.add(equipmentManage);
                        break;
                    case "电池组":
                        if (!fileContext.contains("电池包\t" + strings[2])) {
                            return "电池组必须在电池包下";
                        }
                        equipmentManage = new EquipmentManage();
                        equipmentManage.setEquipmentType("3");
                        equipmentManage.setParentName(strings[2]);
                        equipmentManage.setName(strings[1]);
                        equipmentManage.setProject(projectManage);
                        equipmentManage.setCreateUser(user);
                        equipmentManage.setCreateTime(date);
                        equipmentManage.setUpdateTime(date);
                        newList.add(equipmentManage);
                        break;
                    case "电池单体":
                        if (!fileContext.contains("电池组\t" + strings[2])) {
                            return "电池单体必须在电池组下";
                        }
                        equipmentManage = new EquipmentManage();
                        equipmentManage.setEquipmentType("4");
                        equipmentManage.setParentName(strings[2]);
                        equipmentManage.setName(strings[1]);
                        equipmentManage.setProject(projectManage);
                        equipmentManage.setCreateUser(user);
                        equipmentManage.setCreateTime(date);
                        equipmentManage.setUpdateTime(date);
                        newList.add(equipmentManage);
                        break;
                }
            }
            List<EquipmentManage> deleteList = new ArrayList<>();
            // 去除已有的名字
            for (EquipmentManage old : equipmentManages) {
                boolean flag = false;
                for (EquipmentManage newE : newList) {
                    if (old.getName().equals(newE.getName()) & old.getEquipmentType().equals(newE.getEquipmentType())) {
                        newList.remove(newE);
                        flag = false;
                        break;
                    } else if (!old.getName().equals(newE.getName())) {
                        flag = true;
                    }
                }
                if (flag) {
                    old.setIsValid(0);
                    deleteList.add(old);
                }
            }
            equipmentManageRepository.save(deleteList);
            //先保存父节点
            List<EquipmentManage> parentList =
                    newList.stream()
                            .filter(e -> {
                                return e.getEquipmentType().equals("1") || e.getEquipmentType().equals("2");
                            })
                            .collect(Collectors.toList());
            parentList = equipmentManageRepository.save(parentList);
            //电池组
            List<EquipmentManage> groupList = newList.stream().filter(e -> {
                return e.getEquipmentType().equals("3");
            }).collect(Collectors.toList());
            for (EquipmentManage parent : parentList) {
                if (!parent.getEquipmentType().equals("2")) continue;    //变流器直接跳走
                for (EquipmentManage group : groupList) {
                    if (group.getParentName().equals(parent.getName())) {
                        group.setParent(parent);
                    }
                }
            }
            groupList = equipmentManageRepository.save(groupList);
            //电池单体
            List<EquipmentManage> oneList = newList.stream().filter(e -> {
                return e.getEquipmentType().equals("4");
            }).collect(Collectors.toList());
            for (EquipmentManage parent : groupList) {
                if (!parent.getEquipmentType().equals("3")) continue;    //变流器直接跳走
                for (EquipmentManage one : oneList) {
                    if (one.getParentName().equals(parent.getName())) {
                        one.setParent(parent);
                    }
                }
            }
            equipmentManageRepository.save(oneList);
        } catch (IOException e) {
            e.printStackTrace();
            return "文件读取失败，请稍后再试";
        }
        return null;
    }

    /**
     * 工程配置 -> 对象管理 -> 项目管理 -> 编辑设备树 -> 保存重命名的子节点
     *
     * @param parent_id
     * @param project_id
     * @param name
     * @return
     */
    public void saveEquipmentName(String parent_id, String project_id, String name, String type, String id) {
        //获取当前登录用户
        MyShiroRealm.ShiroUser shiroUser = (MyShiroRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        User user = userRepository.findOne(shiroUser.getId());
        EquipmentManage equipmentManage = equipmentManageRepository.findOne(id);
        if (equipmentManage == null) {
            //如果equipmentManage不存在
            equipmentManage = new EquipmentManage();
            equipmentManage.setCreateTime(new Date());
            equipmentManage.setCreateUser(user);
        }
        if (!(type.equals("1") && type.equals("2"))) { // 当不是变压器和电池包的时候
            equipmentManage.setParent(equipmentManageRepository.findOne(parent_id));
        }
        equipmentManage.setProject(projectManageRepository.findOne(project_id));
        equipmentManage.setName(name);
        equipmentManage.setEquipmentType(type);
        equipmentManage.setUpdateTime(new Date());
        equipmentManageRepository.save(equipmentManage);
    }

    /**
     * 工程配置 -> 对象管理 -> 项目管理 -> 编辑设备树 -> 删除子节点
     *
     * @param id
     * @return
     */
    public void deleteEquipment(String id) {
        EquipmentManage equipment = equipmentManageRepository.findOne(id);
        List<EquipmentManage> list = equipmentManageRepository.findByParentId(id);
        List<EquipmentManage> newList = new ArrayList() {{
            addAll(list);
        }};
        if (list.size() > 0) {   // 如果有子元素就假删除, 这一层是电池组了
            list.forEach(equipmentManage -> {
                newList.addAll(equipmentManageRepository.findByParentId(equipmentManage.getId()));  //这一层是电池单体
            });
            newList.forEach(equipmentManage -> {
                equipmentManage.setIsValid(0);
            });
            equipment.setIsValid(0);
            list.add(equipment);
            equipmentManageRepository.save(newList);
        } else if (StringUtils.isNotBlank(equipment.getCommunication())) {    //如果已经配置过了做个假删除
            equipment.setIsValid(0);
            equipmentManageRepository.save(equipment);
        } else {    //没有配置过就直接删除
            equipmentManageRepository.delete(id);
        }
    }

    /**
     * 工程配置 -> 对象管理 -> 项目管理 -> 编辑设备树 -> 批量添加变流器和电池包 -> 保存
     *
     * @param project_id
     * @param pcs_name
     * @param pcs_low
     * @param pcs_high
     * @param bms_name
     * @param bms_low
     * @param bms_high
     */
    public void saveEquipmentList(String project_id, String pcs_name, Long pcs_low, Long pcs_high, String bms_name, Long bms_low, Long bms_high) {
        ProjectManage projectManage = projectManageRepository.findOne(project_id);
        //获取当前登录用户
        MyShiroRealm.ShiroUser shiroUser = (MyShiroRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        User user = userRepository.findOne(shiroUser.getId());
        Date time = new Date();
        List<EquipmentManage> list = new ArrayList<EquipmentManage>() {{
            addAll(getName(pcs_name, pcs_low, pcs_high, "1", projectManage, user, time));
            addAll(getName(bms_name, bms_low, bms_high, "2", projectManage, user, time));
        }};
        equipmentManageRepository.save(list);
    }

    /**
     * 根据指定的name和最大最小值 新建设备
     *
     * @param name
     * @param low
     * @param high
     * @param type
     * @param projectManage
     * @param user
     * @param time
     * @return
     */
    public List<EquipmentManage> getName(String name, Long low, Long high, String type, ProjectManage projectManage, User user, Date time) {
        List<EquipmentManage> list = new ArrayList();
        for (Long i = low; i <= high; i++) {
            EquipmentManage equipmentManage = new EquipmentManage();
            equipmentManage.setName(i + name);
            equipmentManage.setEquipmentType(type);
            equipmentManage.setProject(projectManage);
            equipmentManage.setCreateTime(time);
            equipmentManage.setUpdateTime(time);
            equipmentManage.setCreateUser(user);
            list.add(equipmentManage);
        }
        return list;
    }

    /**
     * 工程配置 -> 对象管理 -> 项目管理 -> 编辑设备树 -> 编辑
     *
     * @param id
     * @return
     */
    public EquipmentManage findOne(String id) {
        return equipmentManageRepository.findOne(id);
    }

    /**
     * 工程配置 -> 对象管理 -> 项目管理 -> 编辑设备树 -> 保存编辑
     *
     * @param file
     * @param id
     * @param communication
     * @return
     */
    public String saveProjectEditConfigure(MultipartFile file, String id, String communication) {
        EquipmentManage equipmentManage = equipmentManageRepository.findOne(id);
        if (equipmentManage == null) {
            return "获取id错误！！！";
        }
//        if (!file.getOriginalFilename().endsWith(".txt")) {
//            return "文件格式错误，请上传txt文件";
//        }
        if (StringUtils.isBlank(file.getOriginalFilename())) {
            return "文件名不能为空";
        }
        //将文件名命名为 id+时间+文件后缀
        String myFileName = file.getOriginalFilename();
        String fileName = System.currentTimeMillis() + myFileName.substring(myFileName.lastIndexOf("."), myFileName.length());
        saveFile(file, equipmentManage, communication, fileName);
        equipmentManageRepository.save(equipmentManage);
        return null;
    }

    /**
     * 根据id查找到所有的变流器和电池包的树
     *
     * @param project_id
     * @return
     */
    public List<EquipmentManage> findParentByProjectId(String project_id) {
        List result = new ArrayList();
        ProjectManage projectManage = projectManageRepository.findOne(project_id);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", projectManage.getId());
        jsonObject.put("name", projectManage.getName());
        result.add(jsonObject);

        List<EquipmentManage> list = equipmentManageRepository.findParentByProjectId(project_id);
        list.forEach(equipmentManage -> {
            JSONObject jsoObject = new JSONObject();
            jsoObject.put("id", equipmentManage.getId());
            jsoObject.put("pId", project_id);
            jsoObject.put("name", equipmentManage.getName());
            jsoObject.put("type", equipmentManage.getEquipmentType());
            result.add(jsoObject);
        });

        return result;
    }

    /**
     * 工程配置 -> 对象管理 -> 项目管理 -> 编辑设备树 -> 保存批量编辑
     *
     * @param project_id
     * @param ids
     * @param pcs_communication
     * @param bms_communication
     * @param pcs_file
     * @param bms_file
     * @return
     */
    public String saveProjectEditList(String project_id, String ids, String pcs_communication, String bms_communication, MultipartFile pcs_file, MultipartFile bms_file) {
        ProjectManage projectManage = projectManageRepository.findOne(project_id);
        if (StringUtils.isBlank(pcs_file.getOriginalFilename()) || StringUtils.isBlank(bms_file.getOriginalFilename())) {
            return "文件名不能为空";
        }
        String[] idss = ids.split(",");
        List<EquipmentManage> list = equipmentManageRepository.findAll(Arrays.asList(idss));
        if (idss.length != list.size()) {
            return "获取id错误！！！";
        }
        //将文件名命名为 id+时间+文件后缀
        String fileName = "";
        String pcs_file_name = "";
        String bms_file_name = "";
        if (pcs_file != null) {
            fileName = pcs_file.getOriginalFilename();
            pcs_file_name = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."), fileName.length());
        }
        if (bms_file != null) {
            fileName = bms_file.getOriginalFilename();
            bms_file_name = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."), fileName.length());
        }
        for (EquipmentManage equipmentManage : list) {
            if (equipmentManage.getEquipmentType().equals("1")) {
                saveFile(pcs_file, equipmentManage, pcs_communication, pcs_file_name);
            } else {
                saveFile(bms_file, equipmentManage, bms_communication, bms_file_name);
            }
        }
        equipmentManageRepository.save(list);
        return null;
    }

    /**
     * 通用保存文件
     *
     * @param file
     * @param equipmentManage
     * @param communication
     * @param fileName
     * @return
     */
    public EquipmentManage saveFile(MultipartFile file, EquipmentManage equipmentManage, String communication, String fileName) {
        try {
            File pathFile = new File(filePath);
            if (!pathFile.exists()) {//如果文件夹不存在,则创建文件夹
                pathFile.mkdirs();
            }
            if (StringUtils.isNotBlank(equipmentManage.getMessageUrl())) {//如果url不为空 （之前创建过）则删除原文件
                String oldFileUrl = equipmentManage.getMessageUrl();
                File oldFile = new File(oldFileUrl);
                // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
                if (oldFile.exists() && oldFile.isFile()) {
                    oldFile.delete();
                }
            }
            String url = filePath + File.separator + fileName;
            //创建一个文件 路径为url
            File createFile = new File(url);
            createFile.createNewFile();
            file.transferTo(createFile);
            //将url设置给customer
            equipmentManage.setCommunication(communication);
            equipmentManage.setMessageUrl(url);
            equipmentManage.setMessageName(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return equipmentManage;
    }

    /**
     * 找到所有项目下的设备
     *
     * @return
     */
    public List findAllByProjectId(List<DeployTree> deployTrees) {
        List<DeployTree> newList = new ArrayList<DeployTree>() {{
            addAll(deployTrees);
        }};
        for (DeployTree deployTree : deployTrees) {
            List<SpecificationOperator> operators = new ArrayList<SpecificationOperator>() {{
                add(new SpecificationOperator("isValid", "1", "EQ"));
                add(new SpecificationOperator("project.id", deployTree.getId(), "EQ"));
            }};
            MySpecification<EquipmentManage> mySpecifications = new MySpecification<>(operators);
            Sort sort = new Sort(Sort.Direction.DESC, "createTime");
            List<EquipmentManage> list = equipmentManageRepository.findAll(mySpecifications, sort);
            list.forEach(equipmentManage -> {
                DeployTree jsonObject = new DeployTree();
                jsonObject.setId(equipmentManage.getId());
                jsonObject.setProjectId(deployTree.getId());
                if (equipmentManage.getParent() == null) {
                    jsonObject.setpId(deployTree.getId());
                } else {
                    jsonObject.setpId(equipmentManage.getParent().getId());
                }
                jsonObject.setBrand(equipmentManage.getBrand() == null ? " " : equipmentManage.getBrand());
                jsonObject.setName(equipmentManage.getName());
                jsonObject.setType("1");
                newList.add(jsonObject);
            });
        }
        return newList;
    }

    /**
     * 根据项目id找到指定项目下的所有设备
     *
     * @return
     */
    public List<DeployTree> findTreeByProjectId(String id, List<DeployTree> deployTrees) {
        List<DeployTree> newList = new ArrayList<DeployTree>() {{
            addAll(deployTrees);
        }};
        List<SpecificationOperator> operators = new ArrayList<SpecificationOperator>() {{
            add(new SpecificationOperator("isValid", "1", "EQ"));
            add(new SpecificationOperator("project.id", id, "EQ"));
        }};
        MySpecification<EquipmentManage> mySpecifications = new MySpecification<>(operators);
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        List<EquipmentManage> list = equipmentManageRepository.findAll(mySpecifications, sort);
        list.forEach(equipmentManage -> {
            DeployTree jsonObject = new DeployTree();
            jsonObject.setId(equipmentManage.getId());
            if (equipmentManage.getParent() == null) {
                jsonObject.setpId(id);
            } else {
                jsonObject.setpId(equipmentManage.getParent().getId());
            }
            jsonObject.setBrand(equipmentManage.getBrand() == null ? " " : equipmentManage.getBrand());
            jsonObject.setName(equipmentManage.getName());
            jsonObject.setType("1");
            newList.add(jsonObject);
        });
        return newList;
    }

    /**
     * 工程配置 -> 对象管理 -> 项目管理 -> 编辑设备树 -> 批量添加电池组和电池单体 -> 保存
     *
     * @param id
     * @param source
     * @return
     */
    public String saveEquipmentGroup(String id, String source) {
        //项目 和 电池包
        EquipmentManage packageE = equipmentManageRepository.findOne(id);
        if (packageE == null) {
            return "获取电池包错误";
        }
        ProjectManage projectManage = packageE.getProject();
        //同一时间
        Date date = new Date();
        //获取当前登录用户
        MyShiroRealm.ShiroUser shiroUser = (MyShiroRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        User user = userRepository.findOne(shiroUser.getId());
        List<EquipmentManage> list = new ArrayList<>();
        //获取对应的JSONObject进行操作
        JSONArray jsonArray = JSONArray.parseArray(source);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String group_name = jsonObject.getString("group_name");
            EquipmentManage group = equipmentManageRepository.findGroupIfHasTheSameName(group_name, packageE, projectManage);
            if (group == null) {
                group = new EquipmentManage();
            } else {
                return "电池模组名称不能重复";
            }
            group.setName(group_name);
            group.setParent(packageE);
            group.setProject(projectManage);
            group.setCreateTime(date);
            group.setUpdateTime(date);
            group.setCreateUser(user);
            group.setEquipmentType("3");
            group = equipmentManageRepository.save(group);
            String one_name = jsonObject.getString("one_name");
            int one_low = jsonObject.getIntValue("one_low");
            int one_high = jsonObject.getIntValue("one_high");
            for (int j = one_low; j <= one_high; j++) {
                EquipmentManage one = new EquipmentManage();
                one.setName(j + one_name);
                one.setParent(group);
                one.setProject(projectManage);
                one.setCreateTime(date);
                one.setUpdateTime(date);
                one.setCreateUser(user);
                one.setEquipmentType("4");
                list.add(one);
            }
        }
        equipmentManageRepository.save(list);
        return null;
    }

    /**
     * 工程配置 -> 对象管理 -> 模组温度配置 -> 配置 -> 获取所有电池组对应的电池单体
     *
     * @param id
     */
    public List<EquipmentManage> findByParentId(String id) {
        return equipmentManageRepository.findByParentId(id);
    }

    /**
     * 根据删除的项目删除对应的设备 以及其他的东西
     *
     * @param ids
     */
    public void deleteEquipmentByProject(String[] ids) {
        List<EquipmentManage> equipmentManages = equipmentManageRepository.findByProjectIds(ids);
        if (equipmentManages.size() < 1) {  //如果没有设备直接结束
            return;
        }
        // 1. 删除温度配置
        List<EquipmentTemperatureConf> equipmentTemperatureConfs = equipmentTemperatureConfRepository.findByEquipmentList(equipmentManages);
        equipmentTemperatureConfs.forEach(equipmentTemperatureConf -> equipmentTemperatureConf.setIsValid(0));
        equipmentTemperatureConfRepository.save(equipmentTemperatureConfs);
        // 2. 删除报文数据
        List<EquipmentMessageConf> equipmentMessageConfs = equipmentMessageConfRepository.findByEquipmentList(equipmentManages);
        equipmentMessageConfRepository.delete(equipmentMessageConfs);
        // 3. 删除设备
        equipmentManages.forEach(equipmentManage -> equipmentManage.setIsValid(0));
        equipmentManageRepository.save(equipmentManages);
    }

    /**
     * 工程配置 -> 对象管理 -> 设备管理 -> 唯一编号 -> 保存
     *
     * @param id
     * @param code
     * @return
     */
    public String saveEquipmentCode(String id, String code) {
        EquipmentManage codeE = findOneByCode(code);
        if (codeE!=null && (!codeE.getId().equals(id))) {
            return "唯一标识不可重复";
        }
        EquipmentManage equipmentManage = findOne(id);
        equipmentManage.setCode(code);
        equipmentManageRepository.save(equipmentManage);
        return "保存成功";
    }

    /**
     * 根据唯一标识找到对应的设备
     *
     * @param code
     * @return
     */
    public EquipmentManage findOneByCode(String code) {
        return equipmentManageRepository.findByCode(code);
    }

//    -------------------------------------------------------------------------------------------------------- Dai的方法 End

    public List<EquipmentManage> findByProjectId(String id) {
        return equipmentManageRepository.findByProjectId(id);
    }

    public EquipmentManage findOneById(String id) {
        return equipmentManageRepository.findOneById(id);
    }

    public List<EquipmentManage> findAllEquipments(){
        return equipmentManageRepository.findAllEquipments();
    }

    /**
     * 根据项目id找到所有的电池包
     * @param id
     * @return
     */
    public List<EquipmentManage> findEquipments(String id,String equipmentType){
        List<EquipmentManage> equipmentManageList = equipmentManageRepository.findEquipments(id,equipmentType);
        return equipmentManageList;
    }
}
